import java.util.*;

class comparetor implements Comparator<Map.Entry<String, Integer>>{
    @Override
    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
        int a= o2.getValue()-o1.getValue();
        if(a!=0){
            return a;
        }else{
            return o2.getKey().compareTo(o1.getKey());
        }
    }
}
class Solution {
    public java.util.List<String> topKFrequent(String[] words, int k) {
        java.util.List<String> list=new ArrayList<>();
        Map<String, Integer> map=new HashMap<>();
        for(int i=0;i<words.length;i++) {
            if(!map.containsKey(words[i])){
                map.put(words[i], 1);
            }else {
                int old=map.get(words[i]);
                map.put(words[i], old+1);
            }
        }
        Set<Map.Entry<String, Integer>> set=map.entrySet();
        PriorityQueue<Map.Entry<String, Integer>> priorityQueue=new PriorityQueue<>(new comparetor());
        for (Map.Entry<String, Integer> entry : set) {
            priorityQueue.offer(entry);
        }
        for(int i=0;i<k;i++) {
            list.add(priorityQueue.poll().getKey());
        }
        return list;
    }

}
class A extends RuntimeException implements Comparable<Integer>{
    @Override
    public int compareTo(Integer o) {
        return 0;
    }
}